<template>
    <!-- 添加按钮 -->
    <div class="header">
        <h2>用户列表</h2>
        <div>
            <el-button class="userAdd" @click="userAddButton" type="primary">添加用户</el-button>
        </div>
    </div>
    <!-- 添加表单 -->
    <el-dialog v-model="showUserAdd" title="添加用户" width="30%" @closed="resetUserAddForm(ruleFormRef)">
        <el-form :model="UserAddForm" ref="ruleFormRef" :rules="rules">
            <el-form-item prop="username">
                <el-input size="large" v-model="UserAddForm.username" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item prop="password">
                <el-input size="large" v-model="UserAddForm.password" placeholder="请输入密码" />
            </el-form-item>
            <el-form-item prop="email">
                <el-input size="large" v-model="UserAddForm.email" placeholder="请输入邮箱" />
            </el-form-item>
            <el-radio-group v-model="UserAddForm.gender">
                <el-radio :label="'1'">男生</el-radio>
                <el-radio :label="'2'">女生</el-radio>
                <el-radio :label="'3'">保密</el-radio>
            </el-radio-group>
            <el-form-item prop="mobile">
                <el-input size="large" v-model="UserAddForm.mobile" placeholder="请输入手机号码" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitUserAddForm(ruleFormRef)">确定</el-button>
                <el-button @click="resetUserAddForm(ruleFormRef)">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <!-- 用户列表 -->
    <el-table :data="list" style="width: 100%">
        <el-table-column align="center" label="序号" width="100" type="index" :index="1" />
        <el-table-column align="center" label="用户名" width="200">
            <template #default="scope"><span>{{ scope.row.username }}</span></template>
        </el-table-column>
        <el-table-column align="center" label="手机号" width="140">
            <template #default="scope"><span>{{ scope.row.mobile }}</span></template>
        </el-table-column>
        <el-table-column align="center" label="邮箱" width="220">
            <template #default="scope"><span>{{ scope.row.email }}</span></template>
        </el-table-column>
        <el-table-column align="center" label="性别" width="110">
            <template #default="scope">
                <el-tag v-if="scope.row.gender == '1'">男生</el-tag>
                <el-tag type="warning" v-else-if="scope.row.gender == '2'">女生</el-tag>
                <el-tag type="info" v-else="scope.row.gender=='3'">保密</el-tag>
            </template>
        </el-table-column>
        <el-table-column align="center" label="状态" width="110">
            <template #default="scope">
                <el-tag type="success" v-if="scope.row.status == 1">正常</el-tag>
                <el-tag type="danger" v-else="scope.row.status==''">禁用</el-tag>
            </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
            <template #default="scope">
                <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
        </el-table-column>
        <!-- 空状态 -->
        <template #empty><el-empty description="暂无数据" /></template>
    </el-table>
    <!-- 分页 -->
    <el-pagination background layout="prev, pager, next" @current-change="UsersList" v-model:current-page="page"
        :total="total" />
</template>

<script setup lang="ts">
import { deleteUserId, getUsersList, postUsersAdd, changeUserId } from '@/service/user';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { reactive, ref } from 'vue';
const ruleFormRef = ref<FormInstance>()
// 用户列表
const list = ref([] as any)
// 总页码
const total = ref()
// 当前页码
const page = ref(1)
// 添加表单默认状态
const showUserAdd = ref(false)
// 表单的状态 0默认 1新增 2编辑
const fromType = ref(0)
// 用户信息数据类型接口
interface iUser {
    username?: string,
    password?: string,
    email?: string,
    gender?: number,
    mobile?: number,
    id?: number,
}
// 新增用户表单数据
let UserAddForm = reactive<iUser>({})
// 邮箱效验规则
const checkEmail = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback(new Error('请输入邮箱'))
    } else if (!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) {
        callback(new Error("你输入的内容不符合邮箱的格式"))
    } else {
        callback()
    }
}
// 手机号码的效验规则
const checkMobile = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback(new Error('请输入手机号码'))
    } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error("你输入的号码不符合手机号码的格式，请输入正确的号码"))
    } else {
        callback()
    }
}
// 验证规则
const rules = reactive<FormRules>({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 5, message: '用户名最短为五个字符', trigger: 'blur' },
    ],
    email: [{ required: true, validator: checkEmail, trigger: 'blur' }],
    mobile: [{ required: true, validator: checkMobile, trigger: 'blur' }],
})

// 获取用户列表
const UsersList = () => {
    getUsersList(page.value).then((res: any) => {
        console.log(res)
        if (res.errNo === 0) {
            list.value = res.paginate.data
            total.value = res.paginate.total
        }
    })
}
UsersList()
// 添加用户
const submitUserAddForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            // 新增状态
            if (fromType.value === 1) {
                postUsersAdd(UserAddForm).then((res: any) => {
                    console.log(res)
                    if (res.errNo === 0) {
                        ElMessage({
                            message: '用户添加成功！',
                            type: 'success',
                        })
                        UsersList()
                        showUserAdd.value = false
                    } else if (res.errNo === 100000) {
                        for (let item in res.errorBag) {
                            ElMessage({
                                message: res.errorBag[item].join(),
                                type: 'warning',
                            })
                        }
                    }
                })
                // 恢复表单默认状态
                fromType.value = 0
            } else {
                changeUserId(UserAddForm.id as any, UserAddForm as any).then((res: any) => {
                    console.log(res)
                    // 编辑状态
                    if (res.errNo === 0) {
                        ElMessage({
                            message: '用户信息修改成功！',
                            type: 'success',
                        })
                        UsersList()
                        showUserAdd.value = false
                    } else if (res.errNo === 100000) {
                        for (let item in res.errorBag) {
                            ElMessage({
                                message: res.errorBag[item].join(),
                                type: 'warning',
                            })
                        }
                    }
                })
                // 恢复表单默认状态
                fromType.value = 0
            }
        } else {
            ElMessage({
                message: '请检查输入的内容是否符合规则',
                type: 'warning',
            })
            return false
        }
    })
}
// 取消添加
const resetUserAddForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    showUserAdd.value = false
}
// 用户新增
const userAddButton = () => {
    UserAddForm = reactive<iUser>({})
    fromType.value = 1
    showUserAdd.value = true
}
// 用户编辑
const handleEdit = (row: any) => {
    console.log(row)
    fromType.value = 2
    UserAddForm = reactive<iUser>({
        username: row.username,
        password: row.password,
        email: row.email,
        gender: row.gender,
        mobile: row.mobile,
        id: row.id
    })
    showUserAdd.value = true
}
// 用户删除
const handleDelete = (row: any) => {
    console.log(row)
    deleteUserId(row.id).then((res: any) => {
        console.log(res)
        if (res.errNo === 0) {
            ElMessage({
                message: '用户信息删除成功！',
                type: 'error',
            })
            UsersList()
        }
    })
}


</script>

<style scoped>
.el-pagination {
    margin-top: 20px;
    margin-left: 10px;
    margin-bottom: 15px;
}

.el-radio-group {
    margin-bottom: 10px;
}
.header {
    display: flex;
    justify-content: space-between;
    height: 80px;
    line-height: 80px;
    padding: 0 30px;
}
</style>